package com.taxi.driver.data.duty;

import com.taxi.driver.config.DutyStatus;
import com.taxi.driver.data.duty.local.DutyLocalSource;
import com.taxi.driver.data.duty.remote.DutyRemoteSource;
import com.taxi.driver.data.entity.OrderListenerEntity;

import javax.inject.Inject;
import javax.inject.Singleton;

import rx.Observable;

/**
 * 功能描述：HomeFrg和DutyFrg使用的"数据"仓库（出车/收车状态、在线时长、接单数 等）
 */
@Singleton
public class DutyRepository implements DutySource {

    private DutyLocalSource mLocalSource;
    private DutyRemoteSource mRemoteSource;

    @Inject
    public DutyRepository(DutyLocalSource localSource, DutyRemoteSource remoteSource) {
        mLocalSource = localSource;
        mRemoteSource = remoteSource;
    }

    @Override
    public Observable<String> reqDutyStatus(boolean onlyFromRemote) {
        if (onlyFromRemote) {
            return mRemoteSource.reqDutyStatus(true)
                    .doOnNext(s -> mLocalSource.setWorkStatus(DutyStatus.ON_DUTY.equals(s)));
        }
        return mLocalSource.reqDutyStatus(false)
                .switchIfEmpty(
                        mRemoteSource.reqDutyStatus(true)
                                .doOnNext(s -> mLocalSource.setWorkStatus(DutyStatus.ON_DUTY.equals(s)))
                );
    }

    @Override
    public Observable<String> reqOnDuty(double onWorkLng, double onWorkLat, String uploadText) {
        return mRemoteSource.reqOnDuty(onWorkLng, onWorkLat, uploadText)
                .doOnNext(s -> {
                    // 本地缓存"出车"状态
                    mLocalSource.setWorkStatus(true);
                });
    }

    @Override
    public Observable<String> reqOffDuty(double offWorkLng, double offWorkLat, String uploadText) {
        return mRemoteSource.reqOffDuty(offWorkLng, offWorkLat, uploadText)
                .doOnNext(s -> {
                    // 本地缓存"收车"状态
                    mLocalSource.setWorkStatus(false);
                });
    }

    @Override
    public void setWorkStatus(Boolean isWork) {
        mLocalSource.setWorkStatus(isWork);
    }

    @Override
    public Boolean isWork() {
        return mLocalSource.isWork();
    }

    @Override
    public void saveListenerSetting(String driverUuid, OrderListenerEntity entity) {
        mLocalSource.saveListenerSetting(driverUuid, entity);
    }

    @Override
    public OrderListenerEntity getListenerSetting(String driverUuid) {
        return mLocalSource.getListenerSetting(driverUuid);
    }

    @Override
    public Observable<OrderListenerEntity> reqListenerSetting(String driverUuid) {
        return mRemoteSource.reqListenerSetting(driverUuid);
    }

    @Override
    public Observable<String> reqSaveListenerSetting(int remindType, String appointTimeStart, String appointTimeEnd) {
        return mRemoteSource.reqSaveListenerSetting(remindType, appointTimeStart, appointTimeEnd);
    }
}
